<template>
  <a-modal title="通道配置" :width="800" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="通道名称" name="channelName" required>
            <a-input v-model:value="form.channelName" placeholder="请输入名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="公司名称" name="companyName" required>
            <a-input v-model:value="form.companyName" placeholder="公司名称/联系人" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="业务类型" name="businessType" required>
            <a-select v-model:value="form.businessType" allowClear :options="CHANNEL_BUSINESS_TYPE" mode="multiple" placeholder="请选择业务类型" />
            <!-- <DictSelect placeholder="请选择" v-model:value="form.businessType" code="CHANNEL_BUSINESS_TYPE" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="通道类型" name="channelType" required>
            <SmartEnumSelect v-model:value="form.channelType" enumName="ZZB_CHANNEL_TYPE_ENUM" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="是否直连" name="directFlag">
            <a-radio-group v-model:value="form.directFlag">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
            <!-- <a-input v-model:value="form.directFlag" placeholder="请输入" /> -->
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="商户违规通知回调URL" name="notifyUrl">
            <a-input v-model:value="form.notifyUrl" placeholder="请输入" />
          </a-form-item>
        </a-col>
      </a-row>

      <div class="section-title">通道参数配置</div>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="线上成本(%)" name="costOnlineRate" required>
            <a-input-number
              v-model:value="form.costOnlineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="线下成本(%)" name="costOfflineRate" required>
            <a-input-number
              v-model:value="form.costOfflineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="全民业务员线上结算基础费率(%)" name="exhibitionOnlineRate" required>
            <a-input-number
              v-model:value="form.exhibitionOnlineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="全民业务员线下结算基础费率(%)" name="exhibitionOfflineRate" required>
            <a-input-number
              v-model:value="form.exhibitionOfflineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商线上结算基础费率(%)" name="agentOnlineRate" required>
            <a-input-number
              v-model:value="form.agentOnlineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商线下结算基础费率(%)" name="agentOfflineRate" required>
            <a-input-number
              v-model:value="form.agentOfflineRate"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="通道排序" name="num">
            <a-input-number v-model:value="form.num" placeholder="请输入" style="width: 100%" :controls="false" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="代理商分润提现起始金额" name="agentProfitMinDraw" required>
            <a-input-number
              v-model:value="form.agentProfitMinDraw"
              placeholder="请输入"
              :disabled="form.defaultedFlag"
              :max="9999999999"
              :precision="2"
              style="width: 100%"
              :controls="false"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item>
        <a-checkbox v-model:checked="form.defaultedFlag">默认通道参数</a-checkbox>
      </a-form-item>

      <div class="notice-text">
        注意：若无通道参数配置为"默认通道参数"，通道排序为支付收款排序<br />
        默认通道参数为系统默认数值（避免重复填写）
      </div>
    </a-form>

    <template #footer>
      <a-button @click="onReset">重置</a-button>
      <a-button @click="onClose">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </template>
  </a-modal>
</template>

<script setup>
  import { reactive, ref, nextTick, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { channelApi } from '/@/api/business/b-operation/channel/channel-api'
  import { smartSentry } from '/@/lib/smart-sentry'
  import DictSelect from '/@/components/business/comment/DataDictionariesSelect.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import {
    CHANNEL_BUSINESS_TYPE, // 通道业务类型
  } from '/@/constants/dict'

  // ------------------------ 事件 ------------------------
  const emits = defineEmits(['reloadList'])

  // ------------------------ 显示与隐藏 ------------------------
  const visibleFlag = ref(false)
  const formRef = ref()

  // const formDefault = {
  //   channelName: undefined,
  //   companyName: undefined,
  //   businessType: undefined,
  //   notifyUrl: undefined,
  //   costOnlineRate: undefined,
  //   costOfflineRate: undefined,
  //   exhibitionOnlineRate: undefined,
  //   exhibitionOfflineRate: undefined,
  //   agentOnlineRate: undefined,
  //   agentOfflineRate: undefined,
  //   agentProfitMinDraw: undefined,
  //   num: undefined,
  //   defaultedFlag: false
  // };
  //
  // const form = reactive({ ...formDefault });
  const formDefault = {
    channelName: undefined,
    companyName: undefined,
    businessType: undefined,
    channelType: undefined,
    notifyUrl: undefined,
    directFlag: undefined,
    costOnlineRate: undefined,
    costOfflineRate: undefined,
    exhibitionOnlineRate: undefined,
    exhibitionOfflineRate: undefined,
    agentOnlineRate: undefined,
    agentOfflineRate: undefined,
    agentProfitMinDraw: undefined,
    num: undefined,
    defaultedFlag: false,
    dCostOnlineRate: undefined, // 默认线上成本
    dCostOfflineRate: undefined, // 默认线下成本
    dExhibitionOnlineRate: undefined, // 默认全民业务员线上结算基础费率
    dExhibitionOfflineRate: undefined, // 默认全民业务员线下结算基础费率
    dAgentOnlineRate: undefined, // 默认代理商线上结算基础费率
    dAgentOfflineRate: undefined, // 默认代理商线下结算基础费率
    dAgentProfitMinDraw: undefined, // 默认代理商分润提现起始金额
  }

  const form = reactive({ ...formDefault })
  const initialForm = ref(null)
  const validateRate = (rule, value, callback, minVal = 0) => {
    if (!minVal) {
      minVal = 0
    }
    if (value == 0 || (value && (value < minVal || value >= 100))) {
      callback(new Error(`成本/费率必须在 ${minVal} 到 100 之间`))
    } else {
      callback()
    }
  }

  const validateAgentProfitMinDraw = (rule, value, callback) => {
    if (value && value < 0) {
      callback(new Error('代理商分润提现起始金额必须大于0'))
    } else {
      callback()
    }
  }
  const rules = {
    channelName: [{ required: true, message: '通道名称必填' }],
    companyName: [{ required: true, message: '公司名称必填' }],
    businessType: [{ required: true, message: '业务类型必填' }],
    channelType: [{ required: true, message: '通道类型必填' }],
    directFlag: [{ required: true, message: '是否直连必填' }],
    costOnlineRate: [
      { required: true, message: '线上成本必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.dCostOnlineRate)
        },
        trigger: 'blur',
      },
    ],
    costOfflineRate: [
      { required: true, message: '线下成本必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.dCostOfflineRate)
        },
        trigger: 'blur',
      },
    ],
    exhibitionOnlineRate: [
      { required: true, message: '全民业务员线上结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.costOnlineRate)
        },
        trigger: 'blur',
      },
    ],
    exhibitionOfflineRate: [
      { required: true, message: '全民业务员线下结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.costOfflineRate)
        },
        trigger: 'blur',
      },
    ],
    agentOnlineRate: [
      { required: true, message: '代理商线上结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.exhibitionOnlineRate)
        },
        trigger: 'blur',
      },
    ],
    agentOfflineRate: [
      { required: true, message: '代理商线下结算基础费率必填' },
      {
        validator: (rule, value, callback) => {
          validateRate(rule, value, callback, form.exhibitionOfflineRate)
        },
        trigger: 'blur',
      },
    ],
    agentProfitMinDraw: [{ validator: validateAgentProfitMinDraw, trigger: 'blur' }],
  }

  // function show(rowData) {
  //   Object.assign(form, formDefault);
  //   if (rowData && !_.isEmpty(rowData)) {
  //     // 先保存默认参数值
  //     const defaultParams = {
  //       dCostOnlineRate: rowData.dCostOnlineRate,
  //       dCostOfflineRate: rowData.dCostOfflineRate,
  //       dExhibitionOnlineRate: rowData.dExhibitionOnlineRate,
  //       dExhibitionOfflineRate: rowData.dExhibitionOfflineRate,
  //       dAgentOnlineRate: rowData.dAgentOnlineRate,
  //       dAgentOfflineRate: rowData.dAgentOfflineRate,
  //       dAgentProfitMinDraw: rowData.dAgentProfitMinDraw,
  //     };
  //
  //     Object.assign(form, {
  //       id: rowData.id,
  //       channelName: rowData.channelName,
  //       companyName: rowData.companyName,
  //       businessType: rowData.businessType,
  //       notifyUrl: rowData.notifyUrl,
  //       costOnlineRate: rowData.costOnlineRate,
  //       costOfflineRate: rowData.costOfflineRate,
  //       exhibitionOnlineRate: rowData.exhibitionOnlineRate,
  //       exhibitionOfflineRate: rowData.exhibitionOfflineRate,
  //       agentOnlineRate: rowData.agentOnlineRate,
  //       agentOfflineRate: rowData.agentOfflineRate,
  //       agentProfitMinDraw: rowData.agentProfitMinDraw,
  //       num: rowData.num,
  //       defaultedFlag: rowData.defaultedFlag === 1
  //     });
  //
  //     // 设置默认参数值
  //     Object.assign(form, defaultParams);
  //
  //     // 如果是默认参数，使用默认值
  //     if (form.defaultedFlag) {
  //       form.costOnlineRate = form.dCostOnlineRate;
  //       form.costOfflineRate = form.dCostOfflineRate;
  //       form.exhibitionOnlineRate = form.dExhibitionOnlineRate;
  //       form.exhibitionOfflineRate = form.dExhibitionOfflineRate;
  //       form.agentOnlineRate = form.dAgentOnlineRate;
  //       form.agentOfflineRate = form.dAgentOfflineRate;
  //       form.agentProfitMinDraw = form.dAgentProfitMinDraw;
  //     }
  //   }
  //   visibleFlag.value = true;
  //   nextTick(() => {
  //     formRef.value.clearValidate();
  //   });
  // }
  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      // 保存初始状态
      initialForm.value = _.cloneDeep(rowData)

      // 设置表单数据
      Object.assign(form, {
        id: rowData.id,
        channelName: rowData.channelName,
        companyName: rowData.companyName,
        businessType: rowData.businessType,
        channelType: rowData.channelType,
        directFlag: rowData.directFlag,
        notifyUrl: rowData.notifyUrl,
        costOnlineRate: rowData.costOnlineRate,
        costOfflineRate: rowData.costOfflineRate,
        exhibitionOnlineRate: rowData.exhibitionOnlineRate,
        exhibitionOfflineRate: rowData.exhibitionOfflineRate,
        agentOnlineRate: rowData.agentOnlineRate,
        agentOfflineRate: rowData.agentOfflineRate,
        agentProfitMinDraw: rowData.agentProfitMinDraw,
        num: rowData.num,
        defaultedFlag: rowData.defaultedFlag === true,
      })

      // 设置默认参数值
      form.dCostOnlineRate = rowData.dCostOnlineRate
      form.dCostOfflineRate = rowData.dCostOfflineRate
      form.dExhibitionOnlineRate = rowData.dExhibitionOnlineRate
      form.dExhibitionOfflineRate = rowData.dExhibitionOfflineRate
      form.dAgentOnlineRate = rowData.dAgentOnlineRate
      form.dAgentOfflineRate = rowData.dAgentOfflineRate
      form.dAgentProfitMinDraw = rowData.dAgentProfitMinDraw

      // 如果是默认通道参数，使用默认值
      if (form.defaultedFlag) {
        form.costOnlineRate = form.dCostOnlineRate
        form.costOfflineRate = form.dCostOfflineRate
        form.exhibitionOnlineRate = form.dExhibitionOnlineRate
        form.exhibitionOfflineRate = form.dExhibitionOfflineRate
        form.agentOnlineRate = form.dAgentOnlineRate
        form.agentOfflineRate = form.dAgentOfflineRate
        form.agentProfitMinDraw = form.dAgentProfitMinDraw
      }
    }
    visibleFlag.value = true
    nextTick(() => {
      formRef.value.clearValidate()
    })
  }
  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  // function onReset() {
  //   Object.assign(form, formDefault);
  //   formRef.value.clearValidate();
  // }
  function onReset() {
    if (initialForm.value) {
      Object.assign(form, initialForm.value)
    } else {
      Object.assign(form, formDefault)
    }
    formRef.value.clearValidate()
  }

  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  async function save() {
    SmartLoading.show()
    try {
      const saveData = {
        ...form,
        defaultedFlag: !!form.defaultedFlag,
      }

      if (form.id) {
        await channelApi.update(saveData)
      } else {
        await channelApi.add(saveData)
      }
      message.success('操作成功')
      emits('reloadList')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  // 监听默认参数复选框变化
  // watch(() => form.defaultedFlag, (newVal) => {
  //   // 如果勾选了默认参数，禁用所有参数输入框
  //   const paramFields = [
  //     'CostOnlineRate',
  //     'CostOfflineRate',
  //     'ExhibitionOnlineRate',
  //     'ExhibitionOfflineRate',
  //     'AgentOnlineRate',
  //     'AgentOfflineRate',
  //     'AgentProfitMinDraw'
  //   ];
  //
  //   paramFields.forEach(field => {
  //     if(newVal) {
  //       // 使用默认值
  //       form[field] = form[`d${field}`];
  //     }
  //   });
  // });
  watch(
    () => form.defaultedFlag,
    (newVal) => {
      if (newVal) {
        // 如果勾选了默认参数，使用默认值
        form.costOnlineRate = form.dCostOnlineRate
        form.costOfflineRate = form.dCostOfflineRate
        form.exhibitionOnlineRate = form.dExhibitionOnlineRate
        form.exhibitionOfflineRate = form.dExhibitionOfflineRate
        form.agentOnlineRate = form.dAgentOnlineRate
        form.agentOfflineRate = form.dAgentOfflineRate
        form.agentProfitMinDraw = form.dAgentProfitMinDraw
      } else {
        // 如果取消勾选，默认值恢复为初始值
        if (initialForm.value) {
          form.costOnlineRate = initialForm.value.costOnlineRate
          form.costOfflineRate = initialForm.value.costOfflineRate
          form.exhibitionOnlineRate = initialForm.value.exhibitionOnlineRate
          form.exhibitionOfflineRate = initialForm.value.exhibitionOfflineRate
          form.agentOnlineRate = initialForm.value.agentOnlineRate
          form.agentOfflineRate = initialForm.value.agentOfflineRate
          form.agentProfitMinDraw = initialForm.value.agentProfitMinDraw
        }
      }
    },
  )

  defineExpose({
    show,
  })
</script>

<style lang="less" scoped>
  .section-title {
    font-size: 14px;
    font-weight: 500;
    margin: 24px 0 16px;
    color: #1f1f1f;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #1890ff;
    }
  }

  :deep(.ant-form-item) {
    margin-bottom: 16px;

    .ant-form-item-required {
      &::before {
        color: #ff4d4f !important;
        margin-right: 4px;
      }
    }

    .ant-form-item-label {
      padding-bottom: 4px;

      label {
        color: rgba(0, 0, 0, 0.85);
        font-size: 14px;
        height: auto;
      }
    }

    .ant-input,
    .ant-select-selector {
      height: 38px !important;
      padding: 6px 11px;
      font-size: 14px;

      &::placeholder {
        color: #bfbfbf;
      }
    }

    .ant-select-single:not(.ant-select-customize-input) .ant-select-selector {
      height: 38px !important;

      .ant-select-selection-search-input {
        height: 36px;
      }

      .ant-select-selection-item {
        line-height: 36px;
      }
    }

    .ant-input {
      line-height: 24px;
    }
  }

  .notice-text {
    padding: 16px;
    background-color: #f59a23;
    border-radius: 2px;
    color: #ffffff;
    font-size: 14px;
    line-height: 1.5;

    br {
      display: block;
      margin: 8px 0;
      content: '';
    }
  }

  :deep(.ant-modal-footer) {
    display: flex;
    justify-content: center;
    gap: 8px;
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;

    .ant-btn {
      min-width: 80px;
    }
  }
</style>
